package com.sy.util;

import com.alibaba.fastjson.JSON;
import com.sy.entity.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import static com.sy.constant.BusinessConstant.COOKIE_TOKEN_NAME;
import static com.sy.constant.BusinessConstant.REDIS_USER_PREFIX;

/**
 * 用于封装Web层中一些常用的操作
 */
@Component
public class WebOperations {
    @Autowired
    private CookieOperations cookieOperations;

    @Autowired
    private RedisOperations redisOperations;


    /**
     * 获取当前登录用户的信息
     * @return 登录用户的信息
     */
    public User getLoginUser() {
        //从Cookie中获取token信息
        String token = cookieOperations.get(COOKIE_TOKEN_NAME);
        return getUserByToken(token);
    }

    public User getLoginUser(HttpServletRequest req) {
        //从Cookie中获取token信息
        String token = cookieOperations.get(req, COOKIE_TOKEN_NAME);
        return getUserByToken(token);
    }

    private User getUserByToken(String token) {
        //（1）如果不能拿到token信息，则说明用户没有登录
        if (StringUtils.isBlank(token)) {
            return null;
        }
        //（2）如果能够拿到token信息，则此时在redis中取对应的登录信息
        else {
            String redisUserKey = REDIS_USER_PREFIX + token;
            String redisUserJsonStr = redisOperations.get(redisUserKey);
            //(2-1)如果在redis中没有找到对应的数据，则说明没有登录
            if (StringUtils.isBlank(redisUserJsonStr)) {
                return null;
            }
            //(2-2)如果在redis中能找到对应的数据，则说明登录过
            else {
                return JSON.parseObject(redisUserJsonStr, User.class);
            }
        }
    }
}
